package org.port.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.port.R;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;

public class Util {
	public static final String TAG = "Util";
	public static final String FILE_NAME_LOG = "file_log.txt";
	public final static String DENSITY = "density";
	public final static String SCALED_DENSITY = "scaledDensity";
	public final static String DENSITY_DPI = "densityDpi";
	public final static String HEIGHT_PIXELS = "heightPixels";
	public final static String WIDHT_PIXELS = "widthPixels";
	public final static String XDPI = "xDpi";
	public final static String YDPI = "yDpi";
	public final static String DISPLAY_HEIGHT = "displayHeight";
	public final static String DISPLAY_WIDTH = "displayWidth";

	public final static String APP_SIGNATURES = "signatures";

	public final static String LAST_GRID = "last_grid";
	public final static String LAST_TOWN = "last_town";
	public final static String DB_VER = "db_ver";

	public static String fileRead(Context context, String name) {
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					context.openFileInput(name)));
			String tmp = null;
			while ((tmp = br.readLine()) != null) {
				sb.append(tmp + "\n");
			}
			br.close();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "fileRead is failed");
		}
		return sb.toString();
	}

	public static void fileWrite(Context context, String msg) {
		try {
			StringBuffer sb = new StringBuffer(fileRead(context, FILE_NAME_LOG));
			sb.append(msg);
			BufferedWriter bw = new BufferedWriter(
					new OutputStreamWriter(context.openFileOutput(
							FILE_NAME_LOG, Context.MODE_PRIVATE)));
			bw.write(sb.toString());
			bw.flush();
			bw.close();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "fileWrite is failed");
		}
	}

	public static void createLogFileToExternalStorage(Context context,
			String name) {
		File file = new File(context.getExternalFilesDir(null),
				"Log_Weather.txt");
		try {
			InputStream is = context.openFileInput(FILE_NAME_LOG);
			OutputStream os = new FileOutputStream(file);
			byte[] data = new byte[is.available()];
			is.read(data);
			os.write(data);
			is.close();
			os.close();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "createLogFileToExternalStorage " + file);
		}
	}

	public static DisplayMetrics getDisplayMetrics(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		display.getMetrics(metrics);
		return metrics;
	}

	public static Display getDisplay(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		return manager.getDefaultDisplay();
	}

	public static void printSignatures(Context context) {
		PackageInfo info;
		try {
			info = context.getPackageManager().getPackageInfo("org.port",
					PackageManager.GET_SIGNATURES);
			Log.i(TAG, "" + info.toString());
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				Log.i(TAG, "" + md.getDigestLength());
				md.update(signature.toByteArray());

				Log.i(TAG, "" + info.signatures);
				Log.i(TAG,
						"" + Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Account[] getAccounts(Context context) {
		return ((AccountManager) context
				.getSystemService(Context.ACCOUNT_SERVICE)).getAccounts();
	}

	public static SharedPreferences.Editor getPreferEditor(Context context) {
		return getPrefer(context).edit();
	}

	public static SharedPreferences getPrefer(Context context) {
		return context.getSharedPreferences(
				context.getString(R.string.app_name), Context.MODE_PRIVATE);
	}

	public static String httpGetTypeReturn(String address,
			List<NameValuePair> paramList) {
		HttpResponse response;
		String res = null;
		try {
			HttpGet get = new HttpGet(address
					+ URLEncodedUtils.format(paramList, "utf-8"));
			HttpClient client = new DefaultHttpClient();
			HttpParams httpParams = client.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
			HttpConnectionParams.setSoTimeout(httpParams, 10000);

			response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				if (entity == null) {

				} else {
					res = EntityUtils.toString(entity);
				}
			} else {
				int errorCode = response.getStatusLine().getStatusCode();
				Log.e(TAG, "httpGetTypeReturn fail Response Code: " + errorCode);
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}

	public static int getStateImageId(String state) {
		if ("눈/비".equals(state)) {
			state = "눈비";
		}
		switch (WeahterState.toState(state)) {
		case 흐림:
			return R.drawable.wb_cloudy;
		case 맑음:
			return R.drawable.wb_clearly;
		case CLEARLY_N:
			return (R.drawable.wb_clearly_n);
		case 구름조금:
			return (R.drawable.wb_little_cloudy);
		case LITTLE_CLOUDY_N:
			return (R.drawable.wb_little_cloudy_n);
		case 구름많음:
			return (R.drawable.wb_mostly_cloudy);
		case MOSTLY_CLOUDY_N:
			return (R.drawable.wb_mostly_cloudy_n);
		case 비:
			return (R.drawable.wb_rainy);
		case 눈:
			return (R.drawable.wb_snow);
		case 눈비:
			return (R.drawable.wb_snow_rain);
		default:
			return (R.drawable.wb_snow_rain);
		}
	}

	enum WeahterState {
		흐림, 맑음, CLEARLY_N, 구름조금, LITTLE_CLOUDY_N, 구름많음, MOSTLY_CLOUDY_N, 비, 눈, 눈비;

		public static WeahterState toState(String str) {
			Log.d(TAG, "WeahterState toState: " + str);
			return valueOf(str.toUpperCase());
		}
	}

	public static void setKmaImg(ImageView ivState, String state) {
		switch (WeahterState.toState(state)) {
		case 흐림:
			ivState.setImageResource(R.drawable.wb_cloudy);
			break;
		case 맑음:
			ivState.setImageResource(R.drawable.wb_clearly);
			break;
		case CLEARLY_N:
			ivState.setImageResource(R.drawable.wb_clearly_n);
			break;
		case 구름조금:
			ivState.setImageResource(R.drawable.wb_little_cloudy);
			break;
		case LITTLE_CLOUDY_N:
			ivState.setImageResource(R.drawable.wb_little_cloudy_n);
			break;
		case 구름많음:
			ivState.setImageResource(R.drawable.wb_mostly_cloudy);
			break;
		case MOSTLY_CLOUDY_N:
			ivState.setImageResource(R.drawable.wb_mostly_cloudy_n);
			break;
		case 비:
			ivState.setImageResource(R.drawable.wb_rainy);
			break;
		case 눈:
			ivState.setImageResource(R.drawable.wb_snow);
			break;
		case 눈비:
			ivState.setImageResource(R.drawable.wb_snow_rain);
			break;

		default:
			ivState.setImageResource(R.drawable.wb_snow_rain);
			break;
		}
	}
}
